<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>练习记录</span>
        <div style="float: right">
          <el-button type="text" @click="refreshHistory">刷新</el-button>
          <el-button type="text" @click="showStats">统计信息</el-button>
        </div>
      </div>

      <!-- 筛选条件 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onDateChange"
          />
        </el-form-item>
        <el-form-item label="答题结果">
          <el-select v-model="filterForm.isCorrect" placeholder="请选择" clearable @change="onFilterChange">
            <el-option label="正确" :value="true" />
            <el-option label="错误" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getHistoryData">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.totalAnswers }}</div>
              <div class="stats-label">总答题数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.correctAnswers }}</div>
              <div class="stats-label">正确答题数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.correctRate }}%</div>
              <div class="stats-label">正确率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ stats.todayAnswers }}</div>
              <div class="stats-label">今日答题数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 历史记录表格 -->
      <el-table :data="historyList" border style="width: 100%; margin-top: 20px;" v-loading="loading">
        <el-table-column prop="question.title" label="题目标题" show-overflow-tooltip />
        <el-table-column prop="answerContent" label="我的答案" show-overflow-tooltip width="200" />
        <el-table-column prop="isCorrect" label="答题结果" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isCorrect ? 'success' : 'danger'" size="small">
              {{ scope.row.isCorrect ? '正确' : '错误' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question.questionType" label="题目类型" width="100">
          <template slot-scope="scope">
            <el-tag type="info" size="small">
              {{ getQuestionTypeText(scope.row.question.questionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question.difficultyLevel" label="难度级别" width="100">
          <template slot-scope="scope">
            <el-tag :type="getDifficultyType(scope.row.question.difficultyLevel)" size="small">
              {{ getDifficultyText(scope.row.question.difficultyLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewDetails(scope.row)">
              查看详情
            </el-button>
            <el-button size="mini" type="success" @click="practiceAgain(scope.row)">
              再次练习
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="searchModel.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>

    <!-- 答题详情对话框 -->
    <el-dialog title="答题详情" :visible.sync="detailDialogVisible" width="70%">
      <div v-if="selectedRecord">
        <div class="detail-section">
          <h3>题目信息</h3>
          <div class="question-info">
            <p><strong>题目标题：</strong>{{ selectedRecord.question.title }}</p>
            <p><strong>题目内容：</strong></p>
            <div class="question-content">{{ selectedRecord.question.content }}</div>
            <p><strong>题目类型：</strong>
              <el-tag type="info" size="small">{{ getQuestionTypeText(selectedRecord.question.questionType) }}</el-tag>
            </p>
            <p><strong>难度级别：</strong>
              <el-tag :type="getDifficultyType(selectedRecord.question.difficultyLevel)" size="small">
                {{ getDifficultyText(selectedRecord.question.difficultyLevel) }}
              </el-tag>
            </p>
          </div>
        </div>

        <div class="detail-section">
          <h3>我的答案</h3>
          <div class="answer-content">{{ selectedRecord.answerContent }}</div>
        </div>

        <div class="detail-section">
          <h3>答题结果</h3>
          <el-tag :type="selectedRecord.isCorrect ? 'success' : 'danger'" size="medium">
            {{ selectedRecord.isCorrect ? '回答正确' : '回答错误' }}
          </el-tag>
          <p style="margin-top: 10px;">
            <strong>提交时间：</strong>{{ formatDate(selectedRecord.submitTime) }}
          </p>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="practiceAgain(selectedRecord)">再次练习</el-button>
      </div>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog title="统计信息" :visible.sync="statsDialogVisible" width="60%">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <div class="stats-detail">
              <h4>总体统计</h4>
              <p>累计答题：{{ stats.totalAnswers }} 道</p>
              <p>正确答题：{{ stats.correctAnswers }} 道</p>
              <p>错误答题：{{ stats.totalAnswers - stats.correctAnswers }} 道</p>
              <p>正确率：{{ stats.correctRate }}%</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="stats-detail">
              <h4>难度分布</h4>
              <p>简单题目：{{ stats.easyCount }} 道</p>
              <p>中等题目：{{ stats.mediumCount }} 道</p>
              <p>困难题目：{{ stats.hardCount }} 道</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="statsDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userAnswer from '@/api/userAnswer'

export default {
  data() {
    return {
      searchModel: {
        currentPage: 1,
        pageSize: 10
      },
      total: 0,
      historyList: [],
      dateRange: [],
      filterForm: {
        isCorrect: null
      },
      stats: {
        totalAnswers: 0,
        correctAnswers: 0,
        correctRate: 0,
        todayAnswers: 0,
        easyCount: 0,
        mediumCount: 0,
        hardCount: 0
      },
      detailDialogVisible: false,
      statsDialogVisible: false,
      selectedRecord: null,
      loading: false
    }
  },
  computed: {
    userId() {
      return this.$store.getters.userId || 1
    }
  },
  mounted() {
    this.getHistoryData()
    this.getUserStats()
  },
  methods: {
    // 获取历史记录数据
    getHistoryData() {
      this.loading = true
      userAnswer.getUserAnswerHistory(this.userId).then(res => {
        if (res.code === 200) {
          this.historyList = res.data || []
          this.total = this.historyList.length
          this.calculateStats()
        } else {
          this.$message.error(res.message || '获取历史记录失败')
        }
      }).catch(() => {
        this.$message.error('获取历史记录失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取用户统计信息
    getUserStats() {
      userAnswer.getUserStats(this.userId).then(res => {
        if (res.code === 200) {
          this.stats = {
            ...this.stats,
            ...res.data,
            correctRate: Math.round(res.data.correctRate || 0)
          }
        }
      }).catch(() => {
        console.error('获取统计信息失败')
      })
    },

    // 计算统计信息
    calculateStats() {
      const today = new Date().toDateString()

      this.stats.totalAnswers = this.historyList.length
      this.stats.correctAnswers = this.historyList.filter(item => item.isCorrect).length
      this.stats.correctRate = this.stats.totalAnswers > 0
        ? Math.round((this.stats.correctAnswers / this.stats.totalAnswers) * 100)
        : 0

      this.stats.todayAnswers = this.historyList.filter(item => {
        const submitDate = new Date(item.submitTime).toDateString()
        return submitDate === today
      }).length

      // 计算难度分布
      this.stats.easyCount = this.historyList.filter(item =>
        item.question && item.question.difficultyLevel === 'easy'
      ).length
      this.stats.mediumCount = this.historyList.filter(item =>
        item.question && item.question.difficultyLevel === 'medium'
      ).length
      this.stats.hardCount = this.historyList.filter(item =>
        item.question && item.question.difficultyLevel === 'hard'
      ).length
    },

    // 刷新历史记录
    refreshHistory() {
      this.getHistoryData()
      this.getUserStats()
      this.$message.success('刷新成功')
    },

    // 显示统计信息
    showStats() {
      this.statsDialogVisible = true
    },

    // 日期范围变化
    onDateChange() {
      // 可以根据日期范围筛选数据
    },

    // 筛选条件变化
    onFilterChange() {
      // 可以根据筛选条件过滤数据
    },

    // 重置筛选条件
    resetFilter() {
      this.dateRange = []
      this.filterForm.isCorrect = null
      this.getHistoryData()
    },

    // 分页 - 每页显示条数变化
    handleSizeChange(size) {
      this.searchModel.pageSize = size
      this.getHistoryData()
    },

    // 分页 - 当前页变化
    handleCurrentChange(page) {
      this.searchModel.currentPage = page
      this.getHistoryData()
    },

    // 查看详情
    viewDetails(record) {
      this.selectedRecord = record
      this.detailDialogVisible = true
    },

    // 再次练习
    practiceAgain(record) {
      this.$router.push({
        path: '/question/practice',
        query: { questionId: record.questionId }
      })
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    },

    // 获取难度类型样式
    getDifficultyType(level) {
      const typeMap = {
        'easy': 'success',
        'medium': 'warning',
        'hard': 'danger'
      }
      return typeMap[level] || 'info'
    },

    // 获取难度文本
    getDifficultyText(level) {
      const textMap = {
        'easy': '简单',
        'medium': '中等',
        'hard': '困难'
      }
      return textMap[level] || level
    },

    // 获取题目类型文本
    getQuestionTypeText(type) {
      const textMap = {
        'single': '单选题',
        'multiple': '多选题',
        'judge': '判断题',
        'essay': '简答题'
      }
      return textMap[type] || type
    }
  }
}
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px 0;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h3 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.question-info p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.question-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
  line-height: 1.6;
}

.answer-content {
  background-color: #f0f9ff;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  line-height: 1.6;
}

.stats-detail h4 {
  margin-bottom: 15px;
  color: #333;
}

.stats-detail p {
  margin-bottom: 8px;
  line-height: 1.5;
}
</style>
